package com.bhs.sansonglogistics.ui.order;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.AppDatabase;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.ArriveBean;
import com.bhs.sansonglogistics.bean.DedicatedLineBean;
import com.bhs.sansonglogistics.bean.DedicatedLineDataBean;
import com.bhs.sansonglogistics.bean.Driver;
import com.bhs.sansonglogistics.bean.ShipmentsBean;
import com.bhs.sansonglogistics.dialog.BottomSelectArriveAddressDialog;
import com.bhs.sansonglogistics.dialog.BottomSelectiveLineDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.PictureSelectAdapter;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.lxj.xpopup.impl.AttachListPopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;
import wang.relish.widget.vehicleedittext.VehicleKeyboardHelper;

/**
 * 装车发货
 */
public class ShipmentsActivity extends BaseActivity implements View.OnClickListener, TextWatcher, NetCallBack {

    private EditText mEtLicensePlateNumber;
    private EditText mEtDriver;
    private EditText mEtDriverPhoneNumber;
    private TextView mTvSpeciallyLine;
    private TextView mTvBranch;
    private TextView mTvOrder;
    private RecyclerView mRvPicture;
    private TextView mTvShippingCompany;
    private TextView mTvLineManager;
    private TextView mTvPhoneNumber;
    private TextView mTvShipAddress;
    private Button mBtnSubmit;

    private String outlets_id;
    private final int SPECIAL_RAILWAY_LINE = 101;
    private final int PRIVATE_LINE_ORDER_LIST = 102;
    private PictureSelectAdapter pictureSelectAdapter;
    private int type;//1等于订单进来的  2是工作台进来的
    private String reach;
    private String orders;
    private int line_id;
    private AttachListPopupView attachPopup;


    @Override
    public int initLayout() {
        return R.layout.activity_shipments;
    }

    @Override
    public void initView() {
        type = getIntent().getIntExtra("type", 2);
        line_id = getIntent().getIntExtra("line_id", 0);
        orders = getIntent().getStringExtra("deliver_sn");

        mEtLicensePlateNumber = findViewById(R.id.et_license_plate_number);
        VehicleKeyboardHelper.bind(mEtLicensePlateNumber); // 为输入框绑定车牌号输入键盘
        mEtDriver = findViewById(R.id.et_driver);
        mEtDriverPhoneNumber = findViewById(R.id.et_driver_phone_number);
        mTvSpeciallyLine = findViewById(R.id.tv_specially_line);
        mTvSpeciallyLine.setOnClickListener(this);
        mTvBranch = findViewById(R.id.tv_branch);
        mTvOrder = findViewById(R.id.tv_order);
        mTvOrder.setOnClickListener(this);
        mRvPicture = findViewById(R.id.rv_picture);
        mTvShippingCompany = findViewById(R.id.tv_shipping_company);
        mTvLineManager = findViewById(R.id.tv_line_manager);
        mTvPhoneNumber = findViewById(R.id.tv_phone_number);
        mTvShipAddress = findViewById(R.id.tv_ship_address);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mTvBranch.setOnClickListener(this);
        mEtDriver.addTextChangedListener(this);
        mBtnSubmit.setOnClickListener(this);
        mEtDriverPhoneNumber.addTextChangedListener(this);
        mEtDriver.setFilters(MyUtils.inputFilters(this, 20));

    }

    @Override
    public void initData() {
        mTvShippingCompany.setText(String.format("发站公司：%s", SharedPreferencesUtils.getString(this, "company_name")));
        mTvShipAddress.setText(String.format("发站地址：%s", SharedPreferencesUtils.getString(this, "address")));
        pictureSelectAdapter = new PictureSelectAdapter(3, this);
        mRvPicture.setAdapter(pictureSelectAdapter);
        mRvPicture.setLayoutManager(new GridLayoutManager(mContext, 3));
        if (type == 1) {
            networkRequest(netApi.getSpecialLineInfo(line_id), this, SPECIAL_RAILWAY_LINE);
            networkRequest(netApi.getSpecialLineList(line_id, 1, 100), this, PRIVATE_LINE_ORDER_LIST);
            Spanned licensePlateNumber = Html.fromHtml("已选<font color=\"#485EF4\">1</font>单");
            mTvOrder.setText(licensePlateNumber);
        }

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {

                //此处是跳转的result回调方法
                if (result.getData() != null) {
                    orders = result.getData().getStringExtra("orders");
                    Spanned licensePlateNumber = Html.fromHtml("已选<font color=\"#485EF4\">" + orders.split(",").length + "</font>单");
                    mTvOrder.setText(licensePlateNumber);
                }
            }
        });

        mEtLicensePlateNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                verify();
                if (!editable.toString().isEmpty() && editable.toString().length() < 7) {
                    searchAssociation(editable.toString());
                }else {
                    if (attachPopup != null) {
                        attachPopup.dismiss();
                    }
                }
            }
        });


    }

    private void searchAssociation(String toString) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Driver> list = AppDatabase
                        .getInstance(mContext)
                        .getDriverDao()
                        .getAllDriver(toString);

                runOnUiThread(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        if (attachPopup != null) {
                            attachPopup.dismiss();
                        }
                        if (MyUtils.isEmpty(list)) {
                            return;
                        }
                        String[] data = new String[list.size()];
                        for (int i = 0; i < list.size(); i++) {
                            data[i] = list.get(i).getPlateNumber();
                        }

                        attachPopup = new XPopup.Builder(mActivity)
                                .atView(mEtLicensePlateNumber)
                                .isViewMode(true)      //开启View实现
                                .isRequestFocus(false) //不强制焦点
                                .isTouchThrough(true)
                                .hasShadowBg(false)
                                .positionByWindowCenter(true)
                                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                                .asAttachList(data, null, new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        mEtLicensePlateNumber.setText(text);
                                        attachPopup.dismiss();
                                    }
                                });


                        attachPopup.show();
                    }
                });
            }
        }).start();
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == SPECIAL_RAILWAY_LINE) {
            ShipmentsBean shipmentsBean = new Gson().fromJson(json, ShipmentsBean.class);
            if (shipmentsBean.isStatus()) {
                arriveBeans.clear();
                ShipmentsBean.DataDTO.InfoDTO data = shipmentsBean.getData().getInfo();
                arriveBeans.addAll(data.getOutlets_list());
                mTvLineManager.setText(String.format("专线经理：%s", data.getLine_contact()));
                mTvPhoneNumber.setText(String.format("经理手机：%s", data.getLine_mobile()));
            } else {
                ToastUtil.show(shipmentsBean.getMsg());
            }
        } else if (requestCode == PRIVATE_LINE_ORDER_LIST) {
            DedicatedLineDataBean dataBean = new Gson().fromJson(json, DedicatedLineDataBean.class);
            if (dataBean.isStatus()) {
                DedicatedLineBean info = dataBean.getData().getList().get(0);
                reach = info.getStart_city() + "—" + info.getEnd_city();
                reach = reach.replace("市", "");
                Spanned licensePlateNumber = Html.fromHtml(reach
                        + "<font color=\"#485EF4\">(共" + info.getOrder_count() + "单)</font>");
                mTvSpeciallyLine.setText(licensePlateNumber);
            }

        } else {
            BaseBean baseBean = new Gson().fromJson(json, BaseBean.class);
            ToastUtil.show(baseBean.getMsg());
            if (baseBean.isStatus()) {
                finish();
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    private List<ArriveBean> arriveBeans = new ArrayList<>();
    private BottomSelectiveLineDialog bottomSelectiveLineDialog;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_branch:
                if (line_id == 0) {
                    ToastUtil.show("请先选择专线");
                    return;
                }
                BottomSelectArriveAddressDialog addressDialog = new BottomSelectArriveAddressDialog(mContext, arriveBeans);
                new XPopup.Builder(mContext)
                        .asCustom(addressDialog)
                        .show();
                addressDialog.setMyClickListener(new MyClickListener2() {
                    @Override
                    public void onClick(String id, String info) {
                        outlets_id = id;
                        mTvBranch.setText(info);
                        verify();
                    }
                });
                break;
            case R.id.btn_submit:
                submit();
                break;
            case R.id.tv_specially_line:
                if (type == 1) {
                    return;
                }
                if (bottomSelectiveLineDialog == null) {
                    bottomSelectiveLineDialog = new BottomSelectiveLineDialog(this, 1);
                }
                bottomSelectiveLineDialog.setMyClickListener(new MyClickListener2() {
                    @Override
                    public void onClick(String id, String info) {
                        line_id = Integer.parseInt(id);
                        networkRequest(netApi.getSpecialLineInfo(line_id), ShipmentsActivity.this, SPECIAL_RAILWAY_LINE);
                        networkRequest(netApi.getSpecialLineList(line_id, 1, 100), ShipmentsActivity.this, PRIVATE_LINE_ORDER_LIST);
                    }
                });
                bottomSelectiveLineDialog.show();
                break;
            case R.id.tv_order:
                if (line_id == 0) {
                    ToastUtil.show("请先选择专线");
                    return;
                }
                intentActivityResultLauncher.launch(new Intent(ShipmentsActivity.this, SelectOrderActivity.class)
                        .putExtra("orders", orders)
                        .putExtra("line_id", line_id)
                        .putExtra("reach", reach));
                break;
        }
    }

    private void submit() {
        if (!MyUtils.isCarnumberNO(mEtLicensePlateNumber.getText().toString())) {
            ToastUtil.show("请输入正确的车牌号");
            return;
        }
        if (!MyUtils.isPhone(mEtDriverPhoneNumber.getText().toString())) {
            ToastUtil.show("请输入正确的手机号");
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                AppDatabase.getInstance(mActivity)
                        .getDriverDao()
                        .insert(new Driver(mEtLicensePlateNumber.getText().toString()));

            }
        }).start();

        Map<String, String> map = new ArrayMap();
        map.put("deliver_sn", orders);
        map.put("line_id", String.valueOf(line_id));
        map.put("images", pictureSelectAdapter.getImages());
        map.put("license_plate", mEtLicensePlateNumber.getText().toString());
        map.put("driver_name", mEtDriver.getText().toString());
        map.put("driver_mobile", mEtDriverPhoneNumber.getText().toString());
        map.put("outlets_id", outlets_id);
        networkRequest(netApi.confirmDeparture(map), ShipmentsActivity.this);
    }

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }

    private void verify() {
        boolean verify = true;
        if (TextUtils.isEmpty(mEtDriver.getText()) || TextUtils.isEmpty(mEtLicensePlateNumber.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtDriverPhoneNumber.getText()) || TextUtils.isEmpty(mTvBranch.getText())) {
            verify = false;
        }
        mBtnSubmit.setEnabled(verify);
        mBtnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mEtDriver.setFocusable(true);
        mEtDriver.setFocusableInTouchMode(true);
    }
}